package com.guxingke.gblog.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.struts2.interceptor.ServletRequestAware;

import com.guxingke.gblog.dmo.User;
import com.guxingke.gblog.dto.UserDto;
import com.guxingke.gblog.service.UserService;
import com.guxingke.gblog.service.impl.UserServiceImpl;
import com.guxingke.gblog.util.StringUtil;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport implements ServletRequestAware {
	private static final long serialVersionUID = 1L;
	@SuppressWarnings("unused")
	private HttpServletRequest request;
	private UserService userService = new UserServiceImpl();
	private HttpSession session;

	private User user;
	private String error;

	private String mainPage;

	@Override
	public String execute() throws Exception {
		return ERROR;
	}

	public String login() throws Exception {
		if (StringUtil.isEmpty(user.getUsername())
				|| StringUtil.isEmpty(user.getPassword())) {
			error = "用户名或密码不能为空";
			return ERROR;
		}

		UserDto currentUser = userService.login(user);
		if (currentUser == null) {
			error = "用户名或密码错误";
			return ERROR;
		} else {
			session.setAttribute("currentUser", currentUser);
			if (currentUser.getState() != 0) {
				session.setAttribute("admin", currentUser);
				return "manage";
			}
		}
		return SUCCESS;
	}

	public String quit() throws Exception {
		session.invalidate();
		return SUCCESS;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public String getMainPage() {
		return mainPage;
	}

	public void setMainPage(String mainPage) {
		this.mainPage = mainPage;
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
		this.session = request.getSession();
	}
}
